<template>
  <div class="dialog__body">
    <p style="text-indent: 2em">
      <!-- 根据空气压缩机设备的1号压缩机的温度、电机前端振动速度、齿轮箱振动速度、电机后端振动速度、油压等参数的特征变化和对应的历史数据进行训练，采用基于机器学习时间序列算法ARIMA训练生成的故障预测模型。 -->
      {{ rowData.purpose }}
    </p>
    <div class="tab-group">
      <hr />
      <div style="display: flex">
        <div style="width: 30%; padding-right: 5px">
          <div class="title">
            <div>算法输入数据</div>
            <div class="model-button-group">
              <div @click="handleExcute" title="执行">
                <i class="iconfont icon-start-filled"></i>
              </div>
              <!-- 上传 -->
              <el-upload
                id="fileInput"
                v-model="uploadFileList"
                :limit="1"
                :on-progress="handleUpload"
              >
                <div title="上传文件">
                  <i class="iconfont icon-upload-line"></i>
                </div>
              </el-upload>
              <div @click="handleDownload" title="下载文件">
                <i class="iconfont icon-download-line"></i>
              </div>
            </div>
          </div>
          <el-table
            :data="modelData"
            style="width: 100%; display: inline-block"
            :height="tableHeight"
          >
            <el-table-column
              v-for="(item, index) in modelLabelList"
              :key="index"
              :label="item"
              :prop="item"
              show-overflow-tooltip
              width="100"
            >
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="modelNumberChange"
            :total="modelTotal"
            :page-size="modelPageSize"
            :current-page="modelCurrentPage"
            :layout="'total,prev,next,sizes,jumper'"
          >
          </mine-pagination>
        </div>
        <div style="width: 70%">
          <div class="title">
            <div class="run-result">
              <span>运行结果</span>
              <span
                v-if="rowData.resultDesc"
                class="resultDesc"
                :title="rowData.resultDesc"
                >{{ `：(${rowData.resultDesc})` }}</span
              >
            </div>
          </div>
          <div class="show-info">
            <div>
              <span>剩余寿命：</span>
              <span>0天0小时26分钟</span>
            </div>
            <div>
              <span>参数预测置信度：</span>
              <span>1.0000</span>
            </div>
          </div>
          <div
            id="drawEcharts-container"
            style="width: 800px; height: 500px"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  name: "TestResultAram",
  props: {
    rowData: {
      type: Object,
    },
  },
  data() {
    return {
      modelTotal: 0,
      modelPageSize: 10,
      modelCurrentPage: 1,
      modelData: [],
      modelLabelList: [],
      testData: [], // 测试集数据
      previewData: [], // 预测值
      uploadFileList: [], // 上传文件
      isTempFile: 0, // 是否为上传之后的临时文件
    };
  },
  computed: {
    tableHeight: function () {
      return 0.6 * window.innerHeight + "px";
    },
  },
  methods: {
    // 执行按钮
    async handleExcute() {
      await this.getRunResult();
      this.drawEcharts();
    },
    modelNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.modelPageSize = val.pageSize;
          this.getTestModelTableList();
          break;
        case "currentPage":
          this.modelCurrentPage = val.currentPage;
          this.getTestModelTableList();
          break;
        default:
          break;
      }
    },
    drawEcharts() {
      let myChart = this.$echarts.init(
        document.getElementById("drawEcharts-container")
      );
      myChart.setOption({
        // , { type: "slider" }
        dataZoom: [
          { type: "inside", realTime: true },
          { show: true, realTime: true },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: {
          splitStyle: {
            type: "line",
          },
          data: this.xAxisRenderData
            .map((item, index) => {
              let nowTime = new Date();
              let curTime = nowTime - index * 3600000;
              let formatTime = moment(curTime).format("YYYY-MM-DD HH:mm");
              return formatTime.replace(" ", "\n");
            })
            .reverse(),
        },
        yAxis: {
          splitStyle: {
            type: "dashed",
          },
        },
        series: [
          {
            name: "真实值",
            type: "scatter",
            data: this.testData,
            color: "#1895fd",
          },
          {
            name: "预测值",
            type: "line",
            connectNulls: true,
            data: this.previewData,
            color: "#efaa2e",
            symbolSize: 1,
          },
        ],
      });
    },
    async getTestModelTableList() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/algoTemplateFile/testList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                {
                  id: _self.rowData.id,
                  page: _self.modelCurrentPage,
                  pageSize: _self.modelPageSize,
                  temp: _self.isTempFile,
                },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(async function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              await _self.getHundredData();
              _self.drawEcharts();
              _self.modelLabelList = Object.keys(result?.data.list[0]);
              _self.modelData = result.data.list;
              // 分页功能初始化数据
              _self.modelTotal = result.data.rowCount;
              _self.modelCurrentPage = result.data.page;
            } else {
              _self.$message.warning("获取数据失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/algoTemplateFile/testList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            {
              id: this.rowData.id,
              page: this.modelCurrentPage,
              pageSize: this.modelPageSize,
              temp: this.isTempFile,
            },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          async (e) => {
            let res = e.data.response;
            if (res.status === 200) {
              await this.getHundredData();
              this.drawEcharts();
              this.modelLabelList = Object.keys(res?.data.list[0]);
              this.modelData = res.data.list;
              // 分页功能初始化数据
              this.modelTotal = res.data.rowCount;
              this.modelCurrentPage = res.data.page;
              // this.modelPageSize = res.data.data.pageSize;
            } else {
              this.$message.warning("获取数据失败");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getTestModelTableList", {
          id: this.rowData.id,
          page: this.modelCurrentPage,
          pageSize: this.modelPageSize,
          temp: this.isTempFile, // 是否为临时文件
        });
        if (res.data.status === 200) {
          await this.getHundredData();
          this.drawEcharts();
          this.modelLabelList = Object.keys(res?.data.data.list[0]);
          this.modelData = res.data.data.list;
          // 分页功能初始化数据
          this.modelTotal = res.data.data.rowCount;
          this.modelCurrentPage = res.data.data.page;
          // this.modelPageSize = res.data.data.pageSize;
        } else {
          this.$message.warning("获取数据失败");
        }
      }
    },
    // 获取运行结果的数据
    async getRunResult() {
      this.$message.success("开始执行");
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        return new Promise((resolve) => {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/algoTemplateFile/testAlgo?id=${_self.rowData.id}&temp=${_self.isTempFile}`,
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(
                  {
                    id: _self.rowData.id,
                    temp: _self.isTempFile,
                  },
                  { indices: false }
                ),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.previewData = [];
                result.data.forEach((item, index) => {
                  _self.previewData.push([index + 99, item]);
                });
                _self.xAxisRenderData = _self.testData.concat(
                  _self.previewData
                );
                _self.$message.success("执行成功");
                resolve();
              } else {
                _self.$message.warning(result.msg);
              }
            });
          }
        });
      } else if (this.$webview2.isWPF) {
        return new Promise(async (resolve) => {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/algoTemplateFile/testAlgo?id=${this.rowData.id}&temp=${this.isTempFile}`,
            "post",
            "application/json;charset=UTF-8",
            qs.stringify(
              {
                id: this.rowData.id,
                temp: this.isTempFile,
              },
              { indices: false }
            ),
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              if (res.status === 200) {
                this.previewData = []; // 每次执行前先清空
                res.data.forEach((item, index) => {
                  this.previewData.push([index + 99, item]);
                });
                this.xAxisRenderData = this.testData.concat(this.previewData);
                this.$message.success("执行成功");
                resolve();
              } else {
                this.$message.warning(res.msg);
              }
            },
            { once: true }
          );
        });
      } else {
        const res = await this.$store.dispatch("getRunStatusResult", {
          id: this.rowData.id,
          temp: this.isTempFile,
        });
        // 设置数据
        if (res.data.status === 200) {
          this.previewData = [];
          res.data.data.forEach((item, index) => {
            this.previewData.push([index + 99, item]);
          });
          this.xAxisRenderData = this.testData.concat(this.previewData);
          this.$message.success("执行成功");
        } else {
          this.$message.warning(res.data.msg);
        }
      }
    },
    // 获取100个测试集的数据
    getHundredData() {
      return new Promise(async (resolve) => {
        let res = {};
        let _self = this;
        this.testData = [];
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/algoTemplateFile/lastTestList",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(
                  {
                    id: _self.rowData.id,
                    temp: _self.isTempFile,
                  },
                  { indices: false }
                ),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                result.data.forEach((item, index) => {
                  _self.testData.push([index, item]);
                });
                _self.xAxisRenderData = _self.testData;
                resolve();
              } else {
                _self.$message.warning("获取数据失败");
              }
            });
          }
        } else if (_self.$webview2.isWPF) {
          const uuid = _self.$webview2.generateRandomUUID();
          await _self.$webview2.sendWebView2(
            "/algoTemplateFile/lastTestList",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(
              {
                id: _self.rowData.id,
                temp: _self.isTempFile,
              },
              { indices: false }
            ),
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              if (res.status === 200) {
                res.data.forEach((item, index) => {
                  _self.testData.push([index, item]);
                });
                _self.xAxisRenderData = _self.testData;
                resolve();
              } else {
                _self.$message.warning("获取数据失败");
              }
            },
            { once: true }
          );
        } else {
          const res = await _self.$store.dispatch("getHundredData", {
            id: _self.rowData.id,
            temp: _self.isTempFile,
          });
          if (res.data.status === 200) {
            res.data.data.forEach((item, index) => {
              _self.testData.push([index, item]);
            });
            _self.xAxisRenderData = _self.testData;
            resolve();
          } else {
            _self.testData = [];
            _self.$message.warning("获取训练集数据失败！");
          }
        }
      });
    },
    // 执行上传文件
    async handleUpload(uploadFiles, file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = async (e) => {
          formData = e.target.result;
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/algoTemplateFile/uploadTemp?id=${_self.rowData.id}&temp=${_self.isTempFile}`,
                RequestMethod: "post",
                ContentType: "multipart/form-data",
                RequestBody: {
                  file: formData,
                  fileName: file.name,
                },
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                // 回显的重新调用当前页面的请求，传字段temp为1
                _self.isTempFile = 1;
                setTimeout(() => {
                  _self.getTestModelTableList();
                }, 200);
                setTimeout(() => {
                  _self.getRunResult();
                }, 400);
                _self.$message.success(result.msg);
              } else {
                _self.$message.warning(result.msg);
              }
            });
          }
        };
      } else if (this.$webview2.isWPF) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = async (e) => {
          formData = e.target.result;
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/algoTemplateFile/uploadTemp?id=${this.rowData.id}&temp=${this.isTempFile}`,
            "post",
            "multipart/form-data",
            {
              file: formData,
              fileName: file.name,
            },
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            async (e) => {
              let res = e.data.response;
              if (res.status === 200) {
                this.$message.success(res.msg);
                // 回显的重新调用当前页面的请求，传字段temp为1
                this.isTempFile = 1;
                setTimeout(() => {
                  this.getTestModelTableList();
                }, 200);
                await this.getHundredData();
                this.drawEcharts();
              } else {
                this.$message.warning(res.msg);
              }
            },
            {
              once: true,
              capture: true,
            }
          );
        };
      } else {
        const res = await this.$store.dispatch("uploadAlgoFile", {
          file: formData,
          id: this.rowData.id,
          temp: this.isTempFile,
        });
        if (res.data.status === 200) {
          this.$message.success(res.data.msg);
          // 回显的重新调用当前页面的请求，传字段temp为1
          this.isTempFile = 1;

          this.getTestModelTableList();
          await this.getHundredData();
          // await this.getRunResult();
          this.drawEcharts();
        } else {
          this.$message.warning(res.data.msg);
        }
      }
    },
    // 下载文件
    async handleDownload() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/algoTemplateFile/downloadTestList?id=${_self.rowData.id}&temp=${_self.isTempFile}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {
                id: _self.rowData.id,
                temp: _self.isTempFile,
              },
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            //   if (!data) {
            //     console.error("No data received.");
            //   }
            //   res = JSON.parse(data);
            //   const result = res.response || {};
            //   // update the followings
            //   if (result.success && res.webInfo.requestId == uuid) {
            //     // _self.$message.success("删除成功");
            //     // // await this.loadData(true);
            //     // _self.loadOptionData(
            //     //   true,
            //     //   false,
            //     //   _self.$store.state.dictAdmin.currentDirId
            //     // );
            //   } else {
            //     // _self.$message.error(result.msg || "删除失败");
            //   }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/algoTemplateFile/downloadTestList?id=${this.rowData.id}&temp=${this.isTempFile}`,
          "post",
          "application/json;charset=UTF-8",
          {
            id: this.rowData.id,
            temp: this.isTempFile,
          },
          false,
          uuid
        );
      } else {
        const res = await this.$store.dispatch("downloadAlgoFile", {
          id: this.rowData.id,
          temp: this.isTempFile,
        });
      }
    },
  },
  async mounted() {
    setTimeout(() => {
      this.getTestModelTableList();
    }, 200);
    // await this.getHundredData();
    // this.drawEcharts();
    // await this.getRunResult();
  },
};
</script>

<style scoped lang="less">
.title {
  display: flex;
  justify-content: space-between;
  padding-left: 20px;
  font-size: 18px;
  font-weight: 700;
  height: 30px;
  line-height: 30px;
  .resultDesc {
    white-space: nowrap;
    overflow: hidden;
    width: 480px;
    text-overflow: ellipsis;
  }
  .run-result {
    display: flex;
  }
  .model-button-group {
    display: flex;
    div {
      margin: 0px 5px;
    }
    .iconfont:hover {
      cursor: pointer;
      font-size: 20px;
      color: #239ce3;
    }
  }
}
.show-info {
  display: flex;
  justify-content: space-between;
  margin-top: 13px;
  padding: 0px 20px;
}
/deep/.el-table td {
  padding: 0;
}
/deep/.el-table th {
  padding: 0;
}
</style>